/*
 * @描述: 
 * @作者: 约訂
 * @Date: 2024-11-11 09:02:12
 * @LastEditTime: 2024-11-11 09:16:21
 * @修改人员: 约訂
 */
/*
 * @描述:
 * @作者: 约訂
 * @Date: 2023-06-08 10:29:09
 * @LastEditTime: 2024-06-14 11:27:35
 * @修改人员: 约訂
 */
import instance from '../../utils/axios';
import { Method } from 'axios';
import qs from 'qs';
import { ElMessage } from 'element-plus';
import $ from 'jquery';
// import image from '../../assets/image/Loading.gif';
// const Dev = false;
const Dev = import.meta.env.MODE == 'development';

//一般情况下，接口类型会放到一个文件
// 下面两个TS接口，表示要传的参数
interface ReqLogin {
    name: string;
    paw: string;
}
interface ReqStatus {
    id: string;
    navStatus: string;
}
interface LoginApiOption {
    OpenId: string;
    Ip: string;
    UserId: string;
    Password: string;
    ProvinceName: string;
    CityName: string;
    AreaName: string;
    Isp: string;
    Lat: string;
    Lng: string;
}

// Res是返回的参数，T是泛型，需要自己定义，返回对数统一管理***
type Res<T> = Promise<ItypeAPI<T>>;
// 一般情况下响应数据返回的这三个参数，
// 但不排除后端返回其它的可能性，
interface ItypeAPI<T> {
    data: T; //请求的数据，用泛型
    msg: string | null; // 返回状态码的信息，如请求成功等
    code: number; //返回后端自定义的200，404，500这种状态码
}

// qs.stringify(data);
/**
 * Post 请求
 * @param url 请求接口路径
 * @param data 参数
 * @param xSkip 是否重复请求截停（默认 false）
 * @returns
 */
export const Post = (
    url: string,
    data: object,
    xSkip: boolean = false,
    token: any = localStorage.getItem('token')
): Res<object> =>
    // instance.post(url, qs.stringify({ Token: localStorage.getItem('token'), ...data }));
    {
        var hearder: any = {};
        if (!Dev) {
            hearder['headers'] = { 'X-Skip-Interceptor': xSkip };
        }
        return instance.post(
            url,
            qs.stringify({
                Token: token,
                ...data
            }),
            hearder
        );
    };

export const Upload = (url: string, data: any): any =>
    instance
        .post(url, data, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
        })
        .then((res) => {
            console.log('post电影数据', res);
            return res;
        })
        .catch((err) => {
            console.log('错误信息', err);
        });
// // post请求 ，没参数
// export const LogoutAPI = (): Res<null> => instance.post('/admin/logout');

// // post请求，有参数,如传用户名和密码
export const loginAPI = async (data: LoginApiOption): Promise<any> => {
    let { Success, rows, msg } = await instance.post('/Account/Login', qs.stringify(data));
    if (Success) {
        return rows;
    }
    try {
        let { Success, rows, msg } = await instance.post('/Account/Login', qs.stringify(data));
        if (Success) {
            return rows;
        } else {
            throw new Error(msg);
        }
    } catch (error) {
        throw error;
    }
};

/**企业微信扫码登陆 */
export const wxLoginApi = (data: LoginApiOption): Res<string> =>
    instance.post('/Account/WxLogin', qs.stringify(data));

// // post请求 ，没参数，但要路径传参
// export const StatusAPI = (data: ReqStatus): Res<null> =>
//     instance.post(`/productCategory?ids=${data.id}&navStatus=${data.navStatus}`);
// //  get请求，没参数，
// export const FlashSessionListApi = (): Res<null> => instance.get('/flashSession/list');

// get请求，有参数，路径也要传参  (也可能直接在这写类型，不过不建议,大点的项目会维护一麻烦)
export const Get = (url: string, data: object): Res<object> =>
    instance.get(url, {
        params: { ...data, token: localStorage.getItem('token') }
    });
// // get请求，有参数，(如果你不会写类型也可以使用any,不过不建议,因为用了之后 和没写TS一样)
// export const AdminListAPI = (params: any): any => instance.get('/admin/list', { params });

/**
 * 按钮导出 excel 表格接口
 * @param url 导出文件路径
 * @param data 数据项 params 参数
 * @param id 按钮绑定属性的id
 * @param name 导出excel文件名称
 * @param type 接口请求方式 支持 Get、Post、Put、Delete
 */
export const ButtonExcel = (
    url: string,
    data: object,
    id: string,
    name: string = '文件名',
    type: string = 'Get'
) => {
    const methodMap: { [key: string]: Method } = {
        Get: 'get',
        Post: 'post',
        Put: 'put',
        Delete: 'delete'
    };
    const method: Method = methodMap[type];
    // 确保获取到有效的请求方法

    if (method) {
        $('#' + id).attr('disabled', 'disabled');
        var img = `<img style="width:16px;height:16px;margin-left:6px;" src="${image}" />`;
        $('#' + id).append(img);
        (data as any)['Token'] = localStorage.token;
        (instance as any)
            [method.toString()](url, { params: data, responseType: 'blob' })
            .then((res: Blob) => {
                console.log(res);

                const blob = res;
                const reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function (e) {
                    const a = document.createElement('a');
                    a.download = name + '.xls';
                    a.href = e.target!.result as string;
                    console.log(a.href);
                    document.documentElement.appendChild(a);
                    a.click();
                    a.remove();
                };
                $('#' + id).removeAttr('disabled');
                $('#' + id)
                    .find('img')
                    .remove();
            });
    } else {
        console.error(`Invalid request type: ${type}`);
    }
};

/**返回接口的默认地址 */
// export const baseURL = () => {
//     return instance.defaults.baseURL;
// };
export const baseURL = instance.defaults.baseURL;

/**src完整路径拼接 */
export const GetPara = (u: string, d: object) => {
    let tokenInfo = localStorage.getItem('token');
    let src = instance.defaults.baseURL + u + '?' + qs.stringify({ ...d, Token: tokenInfo });
    return src;
};
